﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;
using Microsoft.SharePoint;

namespace Redirection
{
    public class CacheHelper
    {
        private HttpContext _context;

        public CacheHelper(HttpContext context)
        {
            _context = context;
        }

        private void ClearAppCacheKey(string key)
        {
            if (!string.IsNullOrEmpty(key) && _context != null && _context.Cache[key] != null)
            {
                _context.Cache.Remove(key);
            }
        }

        public void ClearAppCacheKey(SPWeb web)
        {
            ClearAppCacheKey(GetCacheKey(web));
        }

        public Dictionary<string, RedirectionInfo> GetCachedRedirections(SPWeb web)
        {
            if(_context == null || _context.Cache == null) throw new ArgumentException("Context/Cache is null");

            return _context.Cache[GetCacheKey(web)] != null ? _context.Cache[GetCacheKey(web)] as Dictionary<string, RedirectionInfo> : null;
        }

        public void SetCachedRedirections(SPWeb web, Dictionary<string, RedirectionInfo> redirections,
                                                 SPList list, double interval)
        {
            if(_context != null)
            {
                _context.Cache.Insert(GetCacheKey(web), redirections,
                                             new SPListCacheDependency(list, interval),
                                             Cache.NoAbsoluteExpiration,
                                             Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }
        }

        private static string GetCacheKey(SPWeb web)
        {
            return string.Format("redirections_{0}", web.ID);
        }
    }
}